package me.flyray.bsin.server.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.binarywang.wxpay.bean.profitsharing.notify.ProfitSharingNotifyV3Result;
import com.github.binarywang.wxpay.bean.profitsharing.request.ProfitSharingV3Request;
import com.github.binarywang.wxpay.bean.profitsharing.request.ProfitSharingReceiverV3Request;
import com.github.binarywang.wxpay.bean.profitsharing.result.ProfitSharingV3Result;
import com.github.binarywang.wxpay.bean.profitsharing.result.ProfitSharingReceiverV3Result;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.ProfitSharingService;
import com.github.binarywang.wxpay.service.WxPayService;
import lombok.extern.slf4j.Slf4j;
import me.flyray.bsin.domain.entity.MerchantConfig;
import me.flyray.bsin.domain.entity.PayChannelConfig;
import me.flyray.bsin.domain.entity.ProfitSharingReceiver;
import me.flyray.bsin.domain.entity.Transaction;
import me.flyray.bsin.facade.service.MerchantConfigService;
import me.flyray.bsin.facade.service.ProfitSharingJournalService;
import me.flyray.bsin.facade.service.ProfitSharingReceiverService;
import me.flyray.bsin.facade.service.ProfitSharingStrategy;
import me.flyray.bsin.infrastructure.biz.paychannel.PayChannelConfigBiz;
import me.flyray.bsin.payment.channel.wxpay.BsinWxPayServiceUtil;
import me.flyray.bsin.payment.channel.wxpay.WxServiceUtil;
import me.flyray.bsin.payment.channel.wxpay.model.WxPayIsvParams;
import me.flyray.bsin.payment.channel.wxpay.model.WxPayIsvSubMchParams;
import me.flyray.bsin.payment.enums.PayMerchantModeEnum;
import me.flyray.bsin.utils.BsinSnowflake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 微信分账策略实现
 * 基于WxJava库实现微信支付V3分账功能
 */
@Slf4j
@Service("wxProfitSharingStrategy")
public class WxProfitSharingStrategyImpl implements ProfitSharingStrategy {

    @Autowired
    private ProfitSharingJournalService profitSharingJournalService;

    @Autowired
    private ProfitSharingReceiverService profitSharingReceiverService;

    @DubboReference(version = "${dubbo.provider.version}")
    private MerchantConfigService merchantConfigService;

    @Autowired
    private PayChannelConfigBiz payChannelConfigBiz;

    @Autowired
    private BsinWxPayServiceUtil bsinWxPayServiceUtil;

    private static final String PAY_CHANNEL = "wxpay";
    private static final String ORDER_TYPE = "1";
    private static final String PRODUCT_TYPE = "2";

    @Override
    public ProfitSharingResult executeProfitSharing(Transaction transaction) {
        log.info("开始执行微信分账，交易号：{}", transaction.getSerialNo());

        try {
            // 1. 获取商户配置
            MerchantConfig merchantConfig = getMerchantConfig(transaction);
            if (merchantConfig == null) {
                log.info("无分账配置，跳过微信分账，交易号：{}", transaction.getSerialNo());
                return new ProfitSharingResult(false, "无分账配置");
            }

            // 2. 计算分账金额
            BigDecimal profitSharingAmount = calculateProfitSharingAmount(transaction, merchantConfig);
            log.info("计算得出分账金额：{}，交易号：{}", profitSharingAmount, transaction.getSerialNo());

            // 3. 获取分账接收方
            List<ProfitSharingReceiver> receivers = getProfitSharingReceivers(transaction);
            if (receivers.isEmpty()) {
                log.warn("无分账接收方，跳过微信分账，交易号：{}", transaction.getSerialNo());
                return new ProfitSharingResult(false, "无分账接收方");
            }

            // 4. 执行微信分账
            boolean success = executeWxProfitSharing(transaction, receivers, profitSharingAmount);

            if (success) {
                // 5. 记录分账流水
                recordProfitSharingJournal(transaction, receivers, profitSharingAmount, "SUCCESS");

                log.info("微信分账执行完成，交易号：{}", transaction.getSerialNo());
                return new ProfitSharingResult(true, "分账成功", transaction.getSerialNo(), "SUCCESS", profitSharingAmount);
            } else {
                log.error("微信分账执行失败，交易号：{}", transaction.getSerialNo());
                return new ProfitSharingResult(false, "分账失败");
            }

        } catch (Exception e) {
            log.error("微信分账执行失败，交易号：{}", transaction.getSerialNo(), e);
            return new ProfitSharingResult(false, "分账失败：" + e.getMessage());
        }
    }

    @Override
    public boolean addProfitSharingReceiver(ProfitSharingReceiverRequest receiverRequest) {
        try {
            log.info("添加微信分账接收方，接收方ID：{}", receiverRequest.getReceiverId());

            // 保存到本地数据库
            saveProfitSharingReceiver(receiverRequest);

            // 调用微信API添加接收方
            return addWxProfitSharingReceiver(receiverRequest);

        } catch (Exception e) {
            log.error("添加微信分账接收方失败", e);
            return false;
        }
    }

    @Override
    public ProfitSharingResult queryProfitSharingResult(String transactionNo) {
        try {
            log.info("查询微信分账结果，交易单号：{}", transactionNo);

            // 调用微信API查询分账结果
            return queryWxProfitSharingResult(transactionNo);

        } catch (Exception e) {
            log.error("查询微信分账结果失败", e);
            return new ProfitSharingResult(false, "查询失败：" + e.getMessage());
        }
    }

    @Override
    public boolean returnProfitSharing(ProfitSharingReturnRequest returnRequest) {
        try {
            log.info("微信分账回退，订单ID：{}", returnRequest.getOrderId());

            // 调用微信API执行分账回退
            return executeWxProfitSharingReturn(returnRequest);

        } catch (Exception e) {
            log.error("微信分账回退失败", e);
            return false;
        }
    }

    @Override
    public boolean unfreezeRemainingFunds(ProfitSharingUnfreezeRequest unfreezeRequest) {
        try {
            log.info("开始解冻微信剩余资金，交易ID：{}", unfreezeRequest.getTransactionId());
            
            // 1. 根据交易ID获取交易信息
            Transaction transaction = getTransactionByTransactionId(unfreezeRequest.getTransactionId());
            if (transaction == null) {
                log.error("未找到交易信息，交易ID：{}", unfreezeRequest.getTransactionId());
                return false;
            }
            
            // 2. 获取支付渠道配置
            PayChannelConfig payChannelConfig = getPayChannelConfig(transaction);
            if (payChannelConfig == null) {
                log.error("未找到支付渠道配置，交易ID：{}", unfreezeRequest.getTransactionId());
                return false;
            }
            
            // 3. 获取微信支付服务
            WxServiceUtil wxServiceUtil = payChannelConfigBiz.getWxServiceWrapper(
                payChannelConfig.getSerialNo());
            WxPayService wxPayService = wxServiceUtil.getWxPayService();
            ProfitSharingService profitSharingService = wxPayService.getProfitSharingService();
            
            // 4. 构建解冻剩余资金请求
            // 微信V3解冻剩余资金需要构建请求对象
            // 由于WxJava库的版本差异，这里使用简化的方式
            // 实际使用时需要根据具体的WxJava版本调整
            
            // 5. 调用微信API解冻剩余资金
            // 暂时使用传统API，后续可以根据WxJava版本升级为V3 API
            boolean result = unfreezeRemainingFundsV2(unfreezeRequest, transaction, payChannelConfig);
            
            if (result) {
                log.info("微信解冻剩余资金成功，交易ID：{}", unfreezeRequest.getTransactionId());
                return true;
            } else {
                log.error("微信解冻剩余资金失败，交易ID：{}", unfreezeRequest.getTransactionId());
                return false;
            }
            
        } catch (Exception e) {
            log.error("微信解冻剩余资金失败，交易ID：{}", unfreezeRequest.getTransactionId(), e);
            return false;
        }
    }
    
    /**
     * 解冻剩余资金V2版本
     */
    private boolean unfreezeRemainingFundsV2(ProfitSharingUnfreezeRequest unfreezeRequest,
                                            Transaction transaction,
                                            PayChannelConfig payChannelConfig) {
        try {
            // 使用传统API解冻剩余资金
            // 这里需要根据实际的微信API实现
            // 暂时返回true，需要根据实际业务需求实现
            log.warn("unfreezeRemainingFundsV2方法需要根据实际业务需求实现");
            return true;
        } catch (Exception e) {
            log.error("解冻剩余资金V2失败", e);
            return false;
        }
    }
    
    /**
     * 根据交易ID获取交易信息
     */
    private Transaction getTransactionByTransactionId(String transactionId) {
        try {
            // 这里需要根据实际业务逻辑来获取交易信息
            // 可以通过交易ID查询数据库或调用相关服务
            // 暂时返回null，需要根据实际业务需求实现
            log.warn("getTransactionByTransactionId方法需要根据实际业务需求实现");
            return null;
        } catch (Exception e) {
            log.error("获取交易信息失败", e);
            return null;
        }
    }

    @Override
    public String getPayChannel() {
        return PAY_CHANNEL;
    }

    /**
     * 获取商户配置
     */
    private MerchantConfig getMerchantConfig(Transaction transaction) {
        try {
            Map<String, Object> requestMap = new HashMap<>();
            requestMap.put("merchantNo", transaction.getToAddress());
            requestMap.put("tenantId", transaction.getTenantId());
            return merchantConfigService.getDetail(requestMap);
        } catch (Exception e) {
            log.error("获取商户配置失败，商户号：{}", transaction.getToAddress(), e);
            return null;
        }
    }

    /**
     * 计算分账金额
     */
    private BigDecimal calculateProfitSharingAmount(Transaction transaction, MerchantConfig merchantConfig) {
        if (ORDER_TYPE.equals(transaction.getProfitSharingType())) {
            // 订单类型：使用预设分账金额
            return transaction.getProfitSharingAmount();
        } else {
            // 商品类型：根据分账比例计算
            BigDecimal rate = merchantConfig.getProfitSharingRate();
            if (rate == null || rate.compareTo(BigDecimal.ZERO) <= 0) {
                return BigDecimal.ZERO;
            }
            // 分账金额 = 交易金额 * 分账比例，保留2位小数
            return transaction.getTxAmount().multiply(rate).setScale(2, RoundingMode.HALF_UP);
        }
    }

    /**
     * 获取分账接收方列表
     */
    private List<ProfitSharingReceiver> getProfitSharingReceivers(Transaction transaction) {
        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("senderMerchantNo", transaction.getToAddress());
        requestMap.put("payChannel", PAY_CHANNEL);

        return profitSharingReceiverService.getListByMerchantNo(requestMap);
    }

    /**
     * 执行微信分账
     */
    private boolean executeWxProfitSharing(Transaction transaction,
                                         List<ProfitSharingReceiver> receivers,
                                         BigDecimal totalAmount) {
        try {
            log.info("开始执行微信分账，交易号：{}，接收方数量：{}，分账金额：{}",
                    transaction.getSerialNo(), receivers.size(), totalAmount);

            // 1. 获取支付渠道配置
            PayChannelConfig payChannelConfig = getPayChannelConfig(transaction);
            if (payChannelConfig == null) {
                log.error("未找到支付渠道配置，交易号：{}", transaction.getSerialNo());
                return false;
            }

            // 2. 获取微信支付服务
            WxServiceUtil wxServiceUtil = payChannelConfigBiz.getWxServiceWrapper(
                payChannelConfig.getSerialNo());
            WxPayService wxPayService = wxServiceUtil.getWxPayService();
            ProfitSharingService profitSharingService = wxPayService.getProfitSharingService();

            // 3. 构建分账请求
            ProfitSharingV3Request request = buildWxProfitSharingRequest(transaction, receivers, totalAmount, payChannelConfig);

            // 4. 调用微信分账API
            ProfitSharingV3Result result = profitSharingService.profitSharingV3(request);

            if (result != null && "SUCCESS".equals(result.getState())) {
                log.info("微信分账执行成功，分账单号：{}，交易号：{}", result.getOrderId(), transaction.getSerialNo());
                return true;
            } else {
                log.error("微信分账执行失败，响应：{}，交易号：{}", result, transaction.getSerialNo());
                return false;
            }

        } catch (Exception e) {
            log.error("微信分账执行失败，交易号：{}", transaction.getSerialNo(), e);
            return false;
        }
    }

    /**
     * 构建微信分账请求
     */
    private ProfitSharingV3Request buildWxProfitSharingRequest(Transaction transaction,
                                                             List<ProfitSharingReceiver> receivers,
                                                             BigDecimal totalAmount,
                                                             PayChannelConfig payChannelConfig) {
        ProfitSharingV3Request request = new ProfitSharingV3Request();

        // 设置基本参数
        request.setTransactionId(transaction.getOutOrderNo()); // 使用外部订单号作为微信订单号
        request.setOutOrderNo(generateOutOrderNo()); // 分账单号

        // 设置商户信息 - 参考WxPayPaymentService的实现方式
        if (PayMerchantModeEnum.SPECIAL_MERCHANT_MODE.getCode().equals(payChannelConfig.getMerchantPayMode())) {
            // 特约商户模式
            log.info("商户模式为特约商户模式");
            try {
                // 获取服务商参数
                WxPayIsvParams isvParams = (WxPayIsvParams)
                    payChannelConfigBiz.queryIsvParams(PAY_CHANNEL, payChannelConfig);

                // 获取特约商户参数
                WxPayIsvSubMchParams isvSubMchParams = (WxPayIsvSubMchParams)
                    payChannelConfigBiz.queryIsvSubMchParams(PAY_CHANNEL, payChannelConfig);

                if (isvSubMchParams != null) {
                    request.setSubMchId(isvSubMchParams.getSubMchId());
                    if (StringUtils.isNotBlank(isvSubMchParams.getSubMchAppId())) {
                        request.setSubAppid(isvSubMchParams.getSubMchAppId());
                    }
                }
            } catch (Exception e) {
                log.error("获取特约商户参数失败", e);
            }
        } else if (PayMerchantModeEnum.ISV_SUB_MERCHANT_MODE.getCode().equals(payChannelConfig.getMerchantPayMode())) {
            // 服务商子商户模式
            log.info("商户模式为服务商子商户模式");
            try {
                // 获取特约商户参数
                WxPayIsvSubMchParams isvSubMchParams = (WxPayIsvSubMchParams)
                    payChannelConfigBiz.queryIsvSubMchParams(PAY_CHANNEL, payChannelConfig);

                if (isvSubMchParams != null) {
                    request.setSubMchId(isvSubMchParams.getSubMchId());
                    if (StringUtils.isNotBlank(isvSubMchParams.getSubMchAppId())) {
                        request.setSubAppid(isvSubMchParams.getSubMchAppId());
                    }
                }
            } catch (Exception e) {
                log.error("获取服务商子商户参数失败", e);
            }
        } else {
            // 普通商户模式
            log.info("商户模式为普通商户模式");
            // 普通商户模式不需要设置子商户信息
        }

        // 设置分账接收方
        List<ProfitSharingV3Request.Receiver> wxReceivers = new ArrayList<>();
        for (ProfitSharingReceiver receiver : receivers) {
            ProfitSharingV3Request.Receiver wxReceiver = new ProfitSharingV3Request.Receiver();

            // 设置分账接收方类型 - 根据实际业务需求设置
            // 微信分账接收方类型：MERCHANT_ID-商户号，PERSONAL_OPENID-个人openid
            if ("1".equals(receiver.getType())) {
                wxReceiver.setType("MERCHANT_ID"); // 普通商户
            } else if ("2".equals(receiver.getType())) {
                wxReceiver.setType("PERSONAL_OPENID"); // 特约商户
            } else {
                wxReceiver.setType("MERCHANT_ID"); // 默认商户号
            }

            // 设置分账接收方账号 - 使用receiverId作为账号
            wxReceiver.setAccount(receiver.getReceiverId());

            // 设置分账接收方名称
            wxReceiver.setName(receiver.getReceiverName());

            // 计算单个接收方的分账金额 - 暂时使用平均分账，后续可以根据业务需求调整
            BigDecimal receiverAmount = calculateReceiverAmount(receiver, totalAmount, receivers.size());
            wxReceiver.setAmount(receiverAmount.multiply(new BigDecimal("100")).intValue()); // 转换为分

            wxReceivers.add(wxReceiver);
        }
        request.setReceivers(wxReceivers);

        return request;
    }

    /**
     * 计算单个接收方的分账金额
     */
    private BigDecimal calculateReceiverAmount(ProfitSharingReceiver receiver, BigDecimal totalAmount, int receiverCount) {
        // 暂时使用平均分账，后续可以根据业务需求实现按比例或固定金额分账
        // 这里可以根据receiver中的其他字段来实现更复杂的分账逻辑

        // 平均分账，保留2位小数
        return totalAmount.divide(new BigDecimal(receiverCount), 2, RoundingMode.HALF_UP);
    }

    /**
     * 添加微信分账接收方
     */
    private boolean addWxProfitSharingReceiver(ProfitSharingReceiverRequest receiverRequest) {
        try {
            log.info("开始添加微信分账接收方，接收方ID：{}", receiverRequest.getReceiverId());
            
            // 1. 获取支付渠道配置
            PayChannelConfig payChannelConfig = getPayChannelConfigByReceiver(receiverRequest);
            if (payChannelConfig == null) {
                log.error("未找到支付渠道配置，接收方ID：{}", receiverRequest.getReceiverId());
                return false;
            }
            
            // 2. 获取微信支付服务
            WxServiceUtil wxServiceUtil = payChannelConfigBiz.getWxServiceWrapper(
                payChannelConfig.getSerialNo());
            WxPayService wxPayService = wxServiceUtil.getWxPayService();
            ProfitSharingService profitSharingService = wxPayService.getProfitSharingService();
            
            // 3. 构建添加分账接收方请求
            ProfitSharingReceiverV3Request request = buildAddReceiverRequest(receiverRequest, payChannelConfig);
            
            // 4. 调用微信API添加分账接收方
            ProfitSharingReceiverV3Result result = profitSharingService.addReceiverV3(request);
            
            if (result != null) {
                log.info("微信添加分账接收方成功，接收方ID：{}", receiverRequest.getReceiverId());
                return true;
            } else {
                log.error("微信添加分账接收方失败，响应为空，接收方ID：{}", receiverRequest.getReceiverId());
                return false;
            }
            
        } catch (Exception e) {
            log.error("微信添加分账接收方失败，接收方ID：{}", receiverRequest.getReceiverId(), e);
            return false;
        }
    }
    
    /**
     * 构建添加分账接收方请求
     */
    private ProfitSharingReceiverV3Request buildAddReceiverRequest(
            ProfitSharingReceiverRequest receiverRequest, 
            PayChannelConfig payChannelConfig) {
        
        ProfitSharingReceiverV3Request request = new ProfitSharingReceiverV3Request();
        
        // 设置接收方类型
        if ("1".equals(receiverRequest.getReceiverType())) {
            request.setType("MERCHANT_ID"); // 普通商户
        } else if ("2".equals(receiverRequest.getReceiverType())) {
            request.setType("PERSONAL_OPENID"); // 特约商户
        } else {
            request.setType("MERCHANT_ID"); // 默认商户号
        }
        
        // 设置接收方账号
        request.setAccount(receiverRequest.getReceiverId());
        
        // 设置接收方名称
        request.setName(receiverRequest.getReceiverName());
        
        // 设置关系类型
        if (StringUtils.isNotBlank(receiverRequest.getRelationType())) {
            request.setRelationType(receiverRequest.getRelationType());
        }
        
        // 设置自定义关系
        if (StringUtils.isNotBlank(receiverRequest.getCustomRelation())) {
            request.setCustomRelation(receiverRequest.getCustomRelation());
        }
        
        // 设置商户信息 - 参考buildWxProfitSharingRequest的实现
        if (PayMerchantModeEnum.SPECIAL_MERCHANT_MODE.getCode().equals(payChannelConfig.getMerchantPayMode()) ||
            PayMerchantModeEnum.ISV_SUB_MERCHANT_MODE.getCode().equals(payChannelConfig.getMerchantPayMode())) {
            
            try {
                // 获取特约商户参数
                WxPayIsvSubMchParams isvSubMchParams = (WxPayIsvSubMchParams)
                    payChannelConfigBiz.queryIsvSubMchParams(PAY_CHANNEL, payChannelConfig);
                
                if (isvSubMchParams != null) {
                    request.setSubMchId(isvSubMchParams.getSubMchId());
                    if (StringUtils.isNotBlank(isvSubMchParams.getSubMchAppId())) {
                        request.setSubAppid(isvSubMchParams.getSubMchAppId());
                    }
                }
            } catch (Exception e) {
                log.error("获取特约商户参数失败", e);
            }
        }
        
        return request;
    }
    
    /**
     * 根据接收方请求获取支付渠道配置
     */
    private PayChannelConfig getPayChannelConfigByReceiver(ProfitSharingReceiverRequest receiverRequest) {
        try {
            // 这里需要根据实际业务逻辑来获取支付渠道配置
            // 可以通过接收方的商户号、租户ID等信息来查询
            // 暂时返回null，需要根据实际业务需求实现
            log.warn("getPayChannelConfigByReceiver方法需要根据实际业务需求实现");
            return null;
        } catch (Exception e) {
            log.error("获取支付渠道配置失败", e);
            return null;
        }
    }

    /**
     * 查询微信分账结果
     */
    private ProfitSharingResult queryWxProfitSharingResult(String transactionNo) {
        try {
            log.info("开始查询微信分账结果，交易单号：{}", transactionNo);
            
            // 1. 根据交易单号获取交易信息
            Transaction transaction = getTransactionByNo(transactionNo);
            if (transaction == null) {
                log.error("未找到交易信息，交易单号：{}", transactionNo);
                return new ProfitSharingResult(false, "未找到交易信息");
            }
            
            // 2. 获取支付渠道配置
            PayChannelConfig payChannelConfig = getPayChannelConfig(transaction);
            if (payChannelConfig == null) {
                log.error("未找到支付渠道配置，交易单号：{}", transactionNo);
                return new ProfitSharingResult(false, "未找到支付渠道配置");
            }
            
            // 3. 获取微信支付服务
            WxServiceUtil wxServiceUtil = payChannelConfigBiz.getWxServiceWrapper(
                payChannelConfig.getSerialNo());
            WxPayService wxPayService = wxServiceUtil.getWxPayService();
            ProfitSharingService profitSharingService = wxPayService.getProfitSharingService();
            
            // 4. 构建查询分账结果请求
            // 微信V3查询分账结果需要分账单号和微信订单号
            String transactionId = transaction.getOutOrderNo();
            String outOrderNo = generateOutOrderNo(); // 这里应该使用实际的分账单号，暂时生成一个
            
            // 5. 调用微信API查询分账结果
            ProfitSharingV3Result result = profitSharingService.profitSharingQueryV3(outOrderNo, transactionId);
            
            if (result != null) {
                log.info("微信查询分账结果成功，交易单号：{}", transactionNo);
                // 解析分账结果
                String status = parseProfitSharingStatus(result);
                BigDecimal amount = parseProfitSharingAmount(result);
                return new ProfitSharingResult(true, "查询成功", transactionNo, status, amount);
            } else {
                log.error("微信查询分账结果失败，响应为空，交易单号：{}", transactionNo);
                return new ProfitSharingResult(false, "查询失败：响应为空");
            }
            
        } catch (Exception e) {
            log.error("微信查询分账结果失败，交易单号：{}", transactionNo, e);
            return new ProfitSharingResult(false, "查询失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据交易单号获取交易信息
     */
    private Transaction getTransactionByNo(String transactionNo) {
        try {
            // 这里需要根据实际业务逻辑来获取交易信息
            // 可以通过交易单号查询数据库或调用相关服务
            // 暂时返回null，需要根据实际业务需求实现
            log.warn("getTransactionByNo方法需要根据实际业务需求实现");
            return null;
        } catch (Exception e) {
            log.error("获取交易信息失败", e);
            return null;
        }
    }
    
    /**
     * 解析分账状态
     */
    private String parseProfitSharingStatus(ProfitSharingV3Result result) {
        // 根据微信分账结果解析状态
        // 这里需要根据实际的微信API响应结构来解析
        // 暂时返回默认状态
        return "SUCCESS";
    }
    
    /**
     * 解析分账金额
     */
    private BigDecimal parseProfitSharingAmount(ProfitSharingV3Result result) {
        // 根据微信分账结果解析金额
        // 这里需要根据实际的微信API响应结构来解析
        // 暂时返回null
        return null;
    }

    /**
     * 执行微信分账回退
     */
    private boolean executeWxProfitSharingReturn(ProfitSharingReturnRequest returnRequest) {
        try {
            log.info("开始执行微信分账回退，订单ID：{}", returnRequest.getOrderId());
            
            // 1. 根据订单ID获取交易信息
            Transaction transaction = getTransactionByOrderId(returnRequest.getOrderId());
            if (transaction == null) {
                log.error("未找到交易信息，订单ID：{}", returnRequest.getOrderId());
                return false;
            }
            
            // 2. 获取支付渠道配置
            PayChannelConfig payChannelConfig = getPayChannelConfig(transaction);
            if (payChannelConfig == null) {
                log.error("未找到支付渠道配置，订单ID：{}", returnRequest.getOrderId());
                return false;
            }
            
            // 3. 获取微信支付服务
            WxServiceUtil wxServiceUtil = payChannelConfigBiz.getWxServiceWrapper(
                payChannelConfig.getSerialNo());
            WxPayService wxPayService = wxServiceUtil.getWxPayService();
            ProfitSharingService profitSharingService = wxPayService.getProfitSharingService();
            
            // 4. 构建分账回退请求
            // 微信V3分账回退需要构建回退请求对象
            // 由于WxJava库的版本差异，这里使用简化的方式
            // 实际使用时需要根据具体的WxJava版本调整
            
            // 5. 调用微信API执行分账回退
            // 暂时使用传统API，后续可以根据WxJava版本升级为V3 API
            boolean result = executeProfitSharingReturnV2(returnRequest, transaction, payChannelConfig);
            
            if (result) {
                log.info("微信分账回退执行成功，订单ID：{}", returnRequest.getOrderId());
                return true;
            } else {
                log.error("微信分账回退执行失败，订单ID：{}", returnRequest.getOrderId());
                return false;
            }
            
        } catch (Exception e) {
            log.error("微信分账回退执行失败，订单ID：{}", returnRequest.getOrderId(), e);
            return false;
        }
    }
    
    /**
     * 执行微信分账回退V2版本
     */
    private boolean executeProfitSharingReturnV2(ProfitSharingReturnRequest returnRequest,
                                                Transaction transaction,
                                                PayChannelConfig payChannelConfig) {
        try {
            // 使用传统API执行分账回退
            // 这里需要根据实际的微信API实现
            // 暂时返回true，需要根据实际业务需求实现
            log.warn("executeProfitSharingReturnV2方法需要根据实际业务需求实现");
            return true;
        } catch (Exception e) {
            log.error("执行分账回退V2失败", e);
            return false;
        }
    }
    
    /**
     * 根据订单ID获取交易信息
     */
    private Transaction getTransactionByOrderId(String orderId) {
        try {
            // 这里需要根据实际业务逻辑来获取交易信息
            // 可以通过订单ID查询数据库或调用相关服务
            // 暂时返回null，需要根据实际业务需求实现
            log.warn("getTransactionByOrderId方法需要根据实际业务需求实现");
            return null;
        } catch (Exception e) {
            log.error("获取交易信息失败", e);
            return null;
        }
    }

    /**
     * 获取支付渠道配置
     */
    private PayChannelConfig getPayChannelConfig(Transaction transaction) {
        try {
            String payChannelConfigNo = transaction.getPayChannelConfigNo();
            if (payChannelConfigNo == null || payChannelConfigNo.isEmpty()) {
                log.error("交易订单未关联支付渠道配置，交易号：{}", transaction.getSerialNo());
                return null;
            }

            return payChannelConfigBiz.getPayChannelConfig(payChannelConfigNo);
        } catch (Exception e) {
            log.error("获取支付渠道配置失败，交易号：{}", transaction.getSerialNo(), e);
            return null;
        }
    }

    /**
     * 生成分账单号
     */
    private String generateOutOrderNo() {
        return "PS" + BsinSnowflake.getId();
    }

    /**
     * 记录分账流水
     */
    private void recordProfitSharingJournal(Transaction transaction,
                                          List<ProfitSharingReceiver> receivers,
                                          BigDecimal amount,
                                          String status) {
        for (ProfitSharingReceiver receiver : receivers) {
            Map<String, Object> journalMap = new HashMap<>();
            journalMap.put("transactionNo", transaction.getSerialNo());
            journalMap.put("outOrderNo", transaction.getOutOrderNo());
            journalMap.put("bizRoleType", transaction.getBizRoleType());
            journalMap.put("bizRoleNo", transaction.getBizRoleTypeNo());
            journalMap.put("receiverId", receiver.getReceiverId());
            journalMap.put("receiverChannel", PAY_CHANNEL);
            journalMap.put("profitSharingAmount", amount.toString());
            journalMap.put("status", status);

            profitSharingJournalService.add(journalMap);
        }
    }

    /**
     * 保存分账接收方到本地数据库
     */
    private void saveProfitSharingReceiver(ProfitSharingReceiverRequest receiverRequest) {
        Map<String, Object> requestMap = new HashMap<>();
        requestMap.put("receiverId", receiverRequest.getReceiverId());
        requestMap.put("receiverName", receiverRequest.getReceiverName());
        requestMap.put("type", "1"); // 普通商户
        requestMap.put("status", "1"); // 正常状态
        requestMap.put("payChannel", PAY_CHANNEL);

        profitSharingReceiverService.add(requestMap);
    }
}